<template>
	<view class="cash">
		<view class="cash-top">
			<view class="leiji">可用余额</view>
			<text class="num"
				style="font-weight: bold;font-size: 60upx;color: #000;margin-bottom: 10px">￥{{ walletmoney }}</text>
			<!-- #ifdef H5 -->
			<view class="tishi">支持微信、支付宝充值，输入充值金额，最低1元</view>
			<!-- #endif -->
			<!-- #ifdef APP-PLUS -->
			<view class="tishi">支持微信、支付宝充值，输入充值金额，最低1元</view>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<view class="tishi">支持微信，输入充值金额，最低1元</view>
			<!-- #endif -->
		</view>

		<view
			style="height: max-content;background-color: #FFFFFF;box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;margin: 0upx 30upx;border-radius: 20upx;">
			<view style="display: flex;flex-direction: row;padding: 35upx 20upx;">
				<view style="font-size: 28upx;color: #333333;font-weight: bold;">充值金额</view>
			</view>
			<view
				style="display: flex;flex-direction: row;padding: 0upx 20upx; margin-top: 10upx;">
				<view style="font-size: 28upx;color: #333333;">¥</view>
				<input type="number" v-model="money" placeholder="请输入金额"
					style="font-size: 30upx;color: #333333;text-align: left;margin-left: 10upx;width: 100%;" />
			</view>
			<view style="background: #E6E6E6;width: 100%;height: 1upx;"></view>

			<view style="display: flex;flex-direction: row;padding: 20upx;margin-top: 20upx;">
				<view style="font-size: 28upx;color: #333333;font-weight: bold;">选择充值方式</view>
			</view>

			<view style="padding: 0 20upx;" v-if="openLists.length > 0">
				<view style="display: flex;height: 100upx;align-items: center;padding-bottom: 20upx;"
					v-for="(item,index) in openLists" :key='index'>
					<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
					<view style="font-size: 30upx;color: #333333;margin-left: 20upx;width: 70%;">{{item.text}}</view>
					<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item)'>
						<label class="tui-radio">
							<radio color="#FF332F" :checked="openWay === item.id ? true : false" />
						</label>
					</radio-group>
				</view>
			</view>
		</view>

		<button style="background: #FF332F;margin: 30upx; border-radius: 50upx;color: #FFFFFF;" @click="recharge">确认支付</button>
		<view style="display: flex;width: 100%;justify-content: center;">
			<view style="color: grey;padding-bottom: 30px;padding-top: 20upx;" @click="goDetail">钱包明细</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				money: '',
				walletmoney: '0',
				providerList: [],
				provider: '',
				disc: '',
				wxShoukuanma: '',
				zfbShoukuanma: '',
				openWay: '1',
				wallet: [],
				CheckRechargevalue: '1',
				openLists: []
			};
		},
		onShow() {
			this.getwalletMoney();
		},
		onLoad(params) {
			this.getCheckRecharge();
			if (params.title) {
				uni.setNavigationBarTitle({
					title: params.title
				})
			}
			this.getwalletMoney();
			// #ifdef  H5
			let openid = this.$queue.getData('openid');
			let userId = this.$queue.getData('userId');
			let that = this;
			if (userId) {
				if (!openid) {
					if (window.location.href.indexOf('?code=') !== -1 || window.location.href.indexOf('&code=') !== -1) {
						let code;
						if (window.location.href.indexOf('?code=') !== -1) {
							code = window.location.href.split('?code=')[1].split('&')[0];
						} else {
							code = window.location.href.split('&code=')[1].split('&')[0];
						}
						if (userId) {
							that.$Request.getT('/user/openId/' + code + '/' + userId).then(res => {
								that.$queue.setData('openid', res.data);
							});
						}
					}
				}
			}
			// #endif
			uni.getProvider({
				service: 'payment',
				success: e => {
					console.log('payment success:' + JSON.stringify(e));
					let providerList = [];
					e.provider.map(value => {
						switch (value) {
							case 'alipay':
								providerList.push({
									name: '支付宝',
									id: value,
									loading: false
								});
								break;
							case 'wxpay':
								providerList.push({
									name: '微信',
									id: value,
									loading: false
								});
								break;
							default:
								break;
						}
					});
					this.providerList = providerList;
				},
				fail: e => {
					console.log('获取支付通道失败：', e);
				}
			});
		},
		methods: {
			previewImg(logourl) {
				let _this = this;
				let imgsArray = [];
				imgsArray[0] = logourl;
				uni.previewImage({
					current: 0,
					urls: imgsArray
				});
			},
			shoukuanma() {
				//微信收款码
				this.$Request.getT('/common/type/173').then(res => {
					if (res.status === 0) {
						this.wxShoukuanma = res.data.value;
					}
				});

				//支付宝收款码
				this.$Request.getT('/common/type/174').then(res => {
					if (res.status === 0) {
						this.zfbShoukuanma = res.data.value;
					}
				});
			},
			getCheckRecharge() {
				this.openLists = [];
				// #ifdef MP-WEIXIN
				this.openWay = '2';
				this.disc = '支持微信，输入充值金额，最低1元';
				let data1 = {};
				data1.id = '2';
				data1.image = 'https://renwu.xiansqx.com/img/20210813/e71382c1b8404e4f96c6d6e89d305329.png';
				data1.text = '微信';
				this.openLists.push(data1);
				// #endif
				// #ifdef APP-PLUS
				this.disc = '支持微信、支付宝充值，输入充值金额，最低1元';
				let data = {};
				data.id = '1';
				data.image = 'https://renwu.xiansqx.com/img/20210813/56cde02b040e453ead8b5d2c0dc17e18.png';
				data.text = '支付宝';
				this.openLists.push(data);
				let data1 = {};
				data1.id = '2';
				data1.image = 'https://renwu.xiansqx.com/img/20210813/e71382c1b8404e4f96c6d6e89d305329.png';
				data1.text = '微信';
				this.openLists.push(data1);
				// #endif
				// #ifdef H5
				let target = navigator.userAgent.toLowerCase();
				let ua = navigator.userAgent.toLowerCase();
				this.openLists = [];
				if (ua.indexOf('micromessenger') !== -1) {
					this.disc = '支持微信充值，输入充值金额，最低1元';
					this.openWay = '2';
					let data1 = {};
					data1.id = '2';
					data1.image = 'https://renwu.xiansqx.com/img/20210813/e71382c1b8404e4f96c6d6e89d305329.png';
					data1.text = '微信';
					this.openLists.push(data1);
				} else {
					this.disc = '支持微信、支付宝充值，输入充值金额，最低1元';
					let data = {};
					data.id = '1';
					data.image = 'https://renwu.xiansqx.com/img/20210813/56cde02b040e453ead8b5d2c0dc17e18.png';
					data.text = '支付宝';
					this.openLists.push(data);
					let data1 = {};
					data1.id = '2';
					data1.image = 'https://renwu.xiansqx.com/img/20210813/e71382c1b8404e4f96c6d6e89d305329.png';
					data1.text = '微信';
					this.openLists.push(data1);
				}
				// #endif
			},
			selectWay: function(item) {
				this.openWay = item.id;
				console.log(this.openWay)
			},
			//获取获取额度
			goDetail() {
				uni.navigateTo({
					url: '/pages/member/moneyList'
				});
			},
			getwalletMoney() {
				let userId = this.$queue.getData('userId');
				this.$Request.getT('/cash/money/' + userId).then(res => {
					if (res.status === 0) {
						this.walletmoney = res.data;
						// this.wallet.push(res.data);
					}
					uni.hideLoading();
				});
			},
			recharge() {
				if (!/^\d+$/.test(this.money)) {
					uni.showToast({
						icon: 'none',
						title: '请输入正确金额，不能包含中文，英文，特殊字符和小数'
					});
					return;
				}
				if (this.money < 1) {
					uni.showToast({
						icon: 'none',
						title: '金额必须大于1元'
					});
					return;
				}
				if (this.openWay == undefined) {
					uni.showToast({
						icon: 'none',
						title: '请选择支付方式'
					});
					return;
				}
				uni.showLoading({
					title: '支付中...'
				});
				let userId = this.$queue.getData('userId');
				//1，支付宝，2，微信
				if (this.openWay == '1') {
					// #ifdef APP-PLUS
					this.$Request.postT('/api/aliPay/payApp?userId=' + userId + '&money=' + this.money).then(
						res => {
							this.isCheckPay(res.status, 'alipay', res.data);
						});
					// #endif
					// #ifdef H5
					this.$Request.postT('/api/aliPay/payH5?money=' + this.money + '&userId=' + userId).then(res => {
						if (res.status === 0) {
							const div = document.createElement('div')
							div.innerHTML = res.data //此处form就是后台返回接收到的数据
							document.body.appendChild(div)
							setTimeout(d => {
								document.forms[0].submit()
							}, 1000)
						} else {
							uni.showToast({
								icon: 'none',
								title: '支付失败!'
							});
						}
					});
					// #endif
				} else if (this.openWay == '2') {
					// #ifdef H5
					let target = navigator.userAgent.toLowerCase();
					let isWeixin = (/micromessenger/.test(target)) ? true : false;
					if (isWeixin) {
						this.$Request.postJson('/api/order/wxPayMoney?userId=' + userId + '&money=' + this.money * 100 +
								'&type=2')
							.then(res => {
								this.callPay(res);
							});
					} else {
						this.$Request.postJson('/api/order/wxPayMoney?userId=' + userId + '&money=' + this.money * 100 +
								'&type=4')
							.then(
								res => {
									const urlArr = window.location.href;
									const hostUrl = urlArr.split("/");
									const callBack = hostUrl[0] + "//" + hostUrl[2] + "/";
									const url = '&redirect_url=' + callBack + 'package/pages/index/recharge';
									window.location = res.data.mweb_url + url
								});
					}
					// #endif
					// #ifdef APP-PLUS
					this.$Request.postJson('/api/order/wxPayMoney?userId=' + userId + '&money=' + this.money * 100 +
						'&type=1').then(
						res => {
							console.log(res)
							this.isCheckPay(res.status, 'wxpay', JSON.stringify(res.data));
						});
					// #endif
					// #ifdef MP-WEIXIN
					this.$Request.postJson('/api/order/wxPayMoney?money=' + this.money * 100 + '&userId=' + userId +
						'&type=3').then(
						res => {
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: res.data.timestamp,
								nonceStr: res.data.noncestr,
								package: res.data.package,
								signType: res.data.signType,
								paySign: res.data.sign,
								success: function(res) {
									uni.showLoading({
										title: '支付成功'
									});
									uni.hideLoading();
								},
								fail: function(err) {
									uni.hideLoading();
									this.$queue.showToast('支付失败');
								}
							});
						});
					// #endif
				}
			},
			callPay: function(response) {
				if (typeof WeixinJSBridge === "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(response), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(response));
						document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(response));
					}
				} else {
					this.onBridgeReady(response);
				}
			},
			onBridgeReady: function(response) {
				let that = this;
				if (!response.package) {
					return;
				}
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": response.appid, //公众号名称，由商户传入
						"timeStamp": response.timestamp, //时间戳，自1970年以来的秒数
						"nonceStr": response.noncestr, //随机串
						"package": response.package,
						"signType": response.signType, //微信签名方式：
						"paySign": response.sign //微信签名
					},
					function(res) {
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							uni.showLoading({
								title: '支付成功'
							});
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							uni.hideLoading();
						}
						WeixinJSBridge.log(response.err_msg);
					}
				);
			},
			isCheckPay(code, name, order) {
				if (code === 0) {
					this.setPayment(name, order);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '支付信息有误'
					});
				}
			},
			setPayment(name, order) {
				uni.requestPayment({
					provider: name,
					orderInfo: order, //微信、支付宝订单数据
					success: function(res) {
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						setTimeout(this.getwalletMoney(), 3000);
					},
					fail: function(err) {
						uni.hideLoading();
					},
					complete() {
						uni.hideLoading();
					}
				});
			}
		}
	};
</script>

<style lang="less" scoped>
	@import '../../static/css/index.css';

	page {
		background: #FFFFFF;
	}

	#shareit {
		-webkit-user-select: none;
		position: fixed;
		/*width: 100%;*/
		height: 2000px;
		background: rgba(0, 0, 0, 0.85);
		text-align: center;
		top: 0;
		left: 0;
		z-index: 999;
	}

	#shareit img {
		max-width: 100%;
	}

	.arrow {
		width: 100px;
		height: 150px;
		position: absolute;
		right: 5%;
		top: 1%;
	}

	#follow {
		margin-right: 60px;
		margin-left: 30px;
		width: 90%;
		height: 50px;
		line-height: 50px;
		text-align: left;
		text-decoration: none;
		font-size: 18px;
		color: white;
		float: left;
		margin-top: 160px;
	}

	.cash {
		position: absolute;
		background-image: url(https://renwu.xiansqx.com/img/20210811/ebb634d85bfe4ec3907d1e1d80998d55.png);
		background-size: 100%;
		width: 100%;
		height: 225upx;
		border-bottom-left-radius: 20upx;

		.cash-top {
			border-radius: 20upx;
			margin: 80upx 30upx 30upx 30upx;
			height: 260upx;
			padding: 30upx 32upx 70upx 30upx;
			width: 92%;
			box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;
			/* border-bottom: 1px solid gainsboro; */
			//background: #e64340;
			//background-image: url(https://renwu.xiansqx.com/img/20210811/ebb634d85bfe4ec3907d1e1d80998d55.png);
			background: #FFFFFF;
			background-size: 100%;
		}

		.leiji {
			font-size: 24upx;
			color: #000;
			margin-bottom: 10px;
		}

		.tishi {
			margin-top: 25upx;
			font-size: 24upx;
			color: #000;
			margin-bottom: 10px;
		}
	}

	.tui-radio {
		display: inline-block;
		padding-left: 28rpx;
		font-size: 36rpx;
		vertical-align: middle;
	}

	.myRadio {
		// height: 16upx;
		// width: 16upx;
		margin-top: 16upx;
		margin-right: 16upx;
	}
</style>